var express = require('express')
var upload = require('../utils/upload')
const movieModel = require('../model/movie')
const {getPreviousDays} = require('../utils/util')
var router = express.Router();


router.post('/upload/img',upload.array('imgFiles'),async (req,res)=>{
    console.log(req.files,'多张图片');
    let allImg = [];

    req.files.forEach((item)=>{
      allImg.push(item.filename)
    })

    if(req.files.length>0) {
        res.send({
          msg:'图片上传成功',
          data:allImg,
          code:1
        })
    } else {
      res.send({
        msg:'图片上传失败',
        code:0
      })
    }
})

// 新建电影  movie/add   formData
// upload.fields 多张图片 多个name 字段对应 的图片
// upload.array('imgSrc',2) :  对应的一个name可以上传多张图片
router.post('/add',upload.fields([
    { name:'imgSrc', maxCount:1},
    { name:'posterSrc', maxCount:1},
    {name:'trailerLink',maxCount:1}
]),async (req,res)=>{
    // console.log(req.body); // 表单数据
    console.log(req.files,'图片信息'); // 图片
    const datas = req.body;
    for(let imgKey in req.files) {
        // 只接受一张
        datas[imgKey]  = req.files[imgKey][0].filename;

        // 支持多张上传
        // let imgArr = [];
        // req.files[imgKey].forEach((info)=>{
        //     imgArr.push(info.filename)
        // })
        // datas[imgKey] = imgArr;
    } 
    // 新增一条数据
   const resData = await  movieModel.create(datas)
    if(resData) {
        res.send({
            data:'ok',
            msg:'添加成功',
            code:1
        })
    } else {
        res.send({
            data:'ok',
            msg:'添加失败',
            code:0
        })
    }
})

// 没有图片上传

router.post('/add',async (req,res)=>{
  const datas = req.body;
     // 新增一条数据
     const resData = await  movieModel.create(datas)
     if(resData) {
         res.send({
             data:'ok',
             msg:'添加成功',
             code:1
         })
     } else {
         res.send({
             data:'ok',
             msg:'添加失败',
             code:0
         })
     }
})
// 编辑影片
router.post('/update',async (req,res)=>{
    const datas = req.body;
     // 新增一条数据
     try {
      const resData = await  movieModel.findByIdAndUpdate(datas._id,datas);
      if(resData) {
          res.send({
              data:'ok',
              msg:'添加成功',
              code:1
          })
      }
     } catch(err){
        res.send({
            data:'ok',
            msg:'添加失败',
            code:0
        })
     }
   
})
// 删除某一条电影
router.delete('/delete',async (req,res)=>{
    // 获取到id
    const id = req.query.id;
    const resData = await movieModel.deleteOne({_id:id});
    if(resData) {
        res.send({
            code:1,
            data:'ok',
            msg:'删除成功'
        })
    } else {
        res.send({
            code:0,
            data:'ok',
            msg:'删除失败'
        })
    }
})
 // 删除多条数据   - 让前端 给一个数组， 数组的每一项是一个id ，字段是ids
router.post('/delete/more', (req,res)=>{
    // 获取到id
    const ids = req.body.ids;  // ['1','2']
    const totalLen = ids.length;
    let curCount=0; 
    ids.forEach(async (id)=>{
        const resData = await movieModel.deleteOne({_id:id});
        if(resData){
            curCount++;
        }
        if(curCount==totalLen){
            // 已经全部删除完毕
            res.send({
                data:'ok',
                msg:'删除成功',
                code:1
            })
        } 
    })
})

// 电影列表  分页 pageIndex 页码，   pageSize:  每页显示多少条数据
router.get('/list',async (req,res)=>{
    const {pageIndex, pageSize,movieType,region,language,title } =  req.query;

    const regex = new RegExp(region, 'i'); // 'i' 标志表示不区分大小写
    // 构建查询条件
    const query = {};
    if (movieType) {
      query.movieType ={
        $regex: movieType,
        $options: 'i' // 可选: 不区分大小写
    };
    }
    if (region) {
      query.region = { $regex: regex };
    }
    if (language) {
      query.language = { $regex: new RegExp(language, 'i') };
    }
    if (title) {
        query.title = { $regex: new RegExp(title, 'i') };
      }

      

   let resData = await movieModel.find(query).skip((pageIndex-1)*pageSize).limit(pageSize).sort({ createdAt: -1 });
   // 总共多少页
   let  count = await movieModel.countDocuments();
   let total = Math.ceil(count / pageSize);
   console.log(count,'总条数');
   console.log(total,'总页码');
   
   if(resData.length>=0) {
        res.send({
            msg:'查询成功',
            code:1,
            total:total,
            data:resData
        })
    } else {
        res.send({
            msg:'查询失败',
            code:0,
            data:resData
        })
    }
   
})

//正在热映
router.get('/hot',async (req,res)=>{  
    const regex = /\d{4}-\d{2}-\d{2}/g;
    const today = new Date();
    const lastDays = getPreviousDays(20);
async function findFutureDates() {
  const docs = await movieModel.find({ release: { $regex: regex } });

  return docs.filter(doc => {
    const dates = doc.release.match(regex);
    return dates.some(date => {
      let parsedDate = new Date(date);
    let lastDays1 = new Date(lastDays);
    console.log(parsedDate);
    console.log(lastDays1);
      return parsedDate <= today && parsedDate>=lastDays1;
    });
  });
}
findFutureDates().then(result => {
    res.send({
        data:result,
        msg:'查询成功',
        code:1
    })
  }).catch(err => {
    console.error(err);
  });
  
})

// 即将上映
router.get('/soon',async (req,res)=>{  
    const regex = /\d{4}-\d{2}-\d{2}/g;
    const today = new Date();

async function findFutureDates() {
  const docs = await movieModel.find({ release: { $regex: regex } });

  return docs.filter(doc => {
    const dates = doc.release.match(regex);
    return dates.some(date => {
      const parsedDate = new Date(date);
      return parsedDate > today;
    });
  });
}
findFutureDates().then(result => {
    console.log(result);
    res.send({
        data:result,
        msg:'查询成功',
        code:1
    })
  }).catch(err => {
    console.error(err);
  });
  
})

// 影片详情
router.get('/detail/:id',async (req,res)=>{
    console.log(req.params.id);
    const detailObj = await movieModel.findById(req.params.id);
   
    res.send({
      data:detailObj,
      msg:'查询成功',
      code:1
  })
    
})
// 根据关键字搜索电影
router.get('/search',async (req,res)=>{
    const {keyword} = req.query;
    let resData = await movieModel.find({title:{
        $regex: keyword, 
        $options:"$i"
    }})
    
    res.send({
        msg:'查询成功',
        code:1,
        data:resData
    })
})


module.exports = router;